package com.itheima.protocol.javaApi;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.ACL;
import org.apache.zookeeper.data.Id;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;
import java.security.acl.Acl;
import java.util.ArrayList;
import java.util.concurrent.CountDownLatch;

/**
 * 创建认证机制
 */
public class AuthControlDemo implements Watcher {

    private final static String CONNECTIONSTRING = "192.168.1.108:2181";
    private final static int SESSIONTIMEOUT = 5000;
    private static CountDownLatch countDownLatch = new CountDownLatch(1);
    private static CountDownLatch countDownLatch2 = new CountDownLatch(1);
    private static ZooKeeper zooKeeper;
    private static Stat stat = new Stat();

    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {

        zooKeeper = new ZooKeeper(CONNECTIONSTRING, SESSIONTIMEOUT, new AuthControlDemo());
        countDownLatch.await();
        System.out.println(zooKeeper.getState());

        ACL acl = new ACL(ZooDefs.Perms.CREATE, new Id("digest", "root:root"));
        ArrayList<ACL> acls = new ArrayList<ACL>();
        acls.add(acl);

        zooKeeper.create("/Auth2","123".getBytes(),acls,CreateMode.PERSISTENT);


        zooKeeper.addAuthInfo("digest", "root:root".getBytes());
        zooKeeper.create("/Auth", "123".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);
        zooKeeper.create("/Auth/auth1-1", "123".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT);

        //创建一个客户端
        ZooKeeper zooKeeper2 = new ZooKeeper(CONNECTIONSTRING, SESSIONTIMEOUT, new AuthControlDemo());
        countDownLatch2.await();
        zooKeeper2.delete("/Auth/auth1-1", -1);
    }

    @Override
    public void process(WatchedEvent watchedEvent) {

        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {

            //Event.EventType.None --> 连接状态
            if (Event.EventType.None == watchedEvent.getType() && null == watchedEvent.getPath()) {

                countDownLatch.countDown();
                countDownLatch2.countDown();
                System.out.println(watchedEvent.getState() + "--->" + watchedEvent.getType());

            }
        }
    }
}
